<?php
namespace app\web\admin;

use app\common\builder\ZBuilder;
use app\web\model\CouponType as myModel;
use app\web\model\Shop;
use app\web\model\Technician;
use app\web\model\Reason;



/**
 * 轮播管理（后台）
 * @package
 */
class Coupontype extends Base 
{
    public $coupon_type = ['平台','店铺','技师'];
    public $check_status = ['待审核','已通过','未通过'];
    public function index(){
        $map = $this->getMap();
        $list = myModel::alias('a')
                        ->where($map)
                        ->leftjoin('shop b','b.id=a.shop_id')
                        ->leftjoin('technician c','c.id=a.technician_id')
                        ->field('a.id,a.coupon_type,a.type_name,a.money,a.full_money,a.status,a.check_status,a.create_time,b.shop_name as shop_id,c.nickName as technician_id')
                        ->paginate();
        return ZBuilder::make('table')
            ->setTableName('coupon_type')
            ->setSearch(['type_name' => '名称']) // 设置搜索参数
            ->addTopButtons(['add','disable','enable','delete'=>['data-tips' => '删除了就无法恢复了']])
            ->addColumns([
                ['id', 'ID'],
                ['coupon_type','所属','status','',$this->coupon_type],
                ['shop_id','所属店铺'],
                ['technician_id','所属技师'],
                ['type_name', '名称'],
                ['money', '面值'],
                ['full_money','满N元可使用'],
                ['status', '状态', 'switch'],
                ['check_status','审核状态','status','',$this->check_status],
                ['right_button', '操作', 'btn'],
            ])
            ->addRightButtons(['edit', 'delete' => ['data-tips' => '删除后无法恢复。']])
            ->addRightButton('check',['title'=>'审核','href'=>url('check',['id'=>'__id__'])])
            ->replaceRightButton(['check_status' => ['in','1,2']], '','check') // 修改id为1的按钮
            ->setRowList($list)
            ->fetch();
    }
    public function check($id)
    {
        $reason = Reason::getSelectAll('status=1','reason');
        $info = myModel::get($id);
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if($data['check_status'] == 2){
                if(!$data['check_desc']) $this->error('请选择不予通过原因');
                $data['check_desc'] = $reason[$data['check_desc']];
            }
            if($data['check_status'] == 0) $this->success('操作成功','index');
            $data['check_time'] = time();
            $data['update_time'] = time();
            
            if($info->save($data)){
                $this->success('操作成功','index');
            }
            $this->error('操作失败');
        }
        
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['static','type_name','卡券名称'],
                ['static','money','面值'],
                ['static','full_money','满N元可使用'],
                ['radio', 'check_status', '审核状态', '', ['未审核','通过','不予通过'], 0],
                ['select','check_desc','不予通过原因','',$reason]
            ])
            ->setTrigger('check_status','2','check_desc')
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 快速编辑
     * @param array $record 行为日志内容
     * @author 蔡伟明 <314013107@qq.com>
     */
    public function quickEdit($record = [])
    {
        $field           = input('post.name', '');
        $value           = input('post.value', '');
        $type            = input('post.type', '');
        $id              = input('post.pk', '');
        $validate        = input('post.validate', '');
        $validate_fields = input('post.validate_fields', '');

        $field == '' && $this->error('缺少字段名');
        $id    == '' && $this->error('缺少主键值');

        $Model = $this->getCurrModel();
        $protect_table = [
            '__ADMIN_USER__',
            '__ADMIN_ROLE__',
            config('database.prefix').'admin_user',
            config('database.prefix').'admin_role',
        ];

        // 验证是否操作管理员
        if (in_array($Model->getTable(), $protect_table) && $id == 1) {
            $this->error('禁止操作超级管理员');
        }

        // 验证器
        if ($validate != '') {
            $validate_fields = array_flip(explode(',', $validate_fields));
            if (isset($validate_fields[$field])) {
                $result = $this->validate([$field => $value], $validate.'.'.$field);
                if (true !== $result) $this->error($result);
            }
        }

        switch ($type) {
            // 日期时间需要转为时间戳
            case 'combodate':
                $value = strtotime($value);
                break;
            // 开关
            case 'switch':
                $value = $value == 'true' ? 1 : 0;
                break;
            // 开关
            case 'password':
                $value = Hash::make((string)$value);
                break;
        }

        // 主键名
        $pk     = $Model->getPk();
        $data = myModel::get($id);
        if($data['coupon_type'] > 0){
            $this->error('只可修改平台优惠券的状态');
        }
        $result = $Model->where($pk, $id)->setField($field, $value);

        cache('hook_plugins', null);
        cache('system_config', null);
        cache('access_menus', null);
        if (false !== $result) {
            // 记录行为日志
            if (!empty($record)) {
                call_user_func_array('action_log', $record);
            }
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    public function add()
    {
        # 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result = $this->validate($data,'CouponType');
            if($result !== true) $this->error($result);
            if (myModel::create($data)) {
                $this->success('新增成功','index');
            } else {
                $this->error('新增失败');
            }
        }
        #获取数据，渲染模板
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'type_name', '名称', '必填'],
                ['number', 'money', '面值', '必填'],
                ['number', 'full_money', '满N元可使用', '必填'],
                ['radio', 'status', '状态', '', ['禁用', '启用'], 1],
            ])
            ->fetch();
    }

    public function edit($id = null){
        $info = MyModel::get($id);
        # 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result = $this->validate($data,'CouponType');
            if($result !== true) $this->error($result);
            if ($info->save($data)) {
                $this->success('编辑成功','index');
            } else {
                $this->error('编辑失败');
            }
        }

        #获取数据，渲染模板
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden','id'],
                ['text', 'type_name', '名称', '必填'],
                ['number', 'money', '面值', '必填'],
                ['number', 'full_money', '满N元可使用', '必填'],
                ['radio', 'status', '状态', '', ['禁用', '启用'], 1],
            ])
            ->setFormData($info)
            ->fetch();
    }
   /**
     * 删除
     * [delete description]
     * @param  array  $record [description]
     * @return [type]         [description]
     */
    public function delete($record = [])
    {
        $ids   = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids   = (array)$ids;
        myModel::destroy($ids);
        $this->success('操作成功');
    }
}